package dao;

import entity.Address;
import entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class AddressDao {
    //增
    public int add(Address address, Connection connection) throws SQLException {
        String sql = "insert into address(province,city,status,street,address_info) values (?,?,?,?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, address.getProvince());
        statement.setString(2, address.getCity());
        statement.setString(3, address.getStatus());
        statement.setString(4, address.getStreet());
        statement.setString(5, address.getAddressInfo());

        int count = statement.executeUpdate();
        statement.close();
        return count;
    }




    //删
    public int delete(int addressId, Connection connection) throws SQLException {
        String sql = "delete from address where address_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,addressId);

        int count = statement.executeUpdate();


        statement.close();
        return count;

    }





    //改
        public int update(Address address, Connection connection) throws SQLException {
            String sql = "update address set province = ?,city = ?,status = ?,street = ?,address_info = ? where address_id = ?";
            PreparedStatement statement = connection.prepareStatement(sql);
            statement.setString(1, address.getProvince());
            statement.setString(2, address.getCity());
            statement.setString(3, address.getStatus());
            statement.setString(4, address.getStreet());
            statement.setString(5, address.getAddressInfo());
            statement.setInt(6, address.getAddressId());
            int count = statement.executeUpdate();
            statement.close();
            return count;
        }
    //查
    public Address selectById(int addressId, Connection connection) throws SQLException {
        String sql = "select * from address where address_id = ?";
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1, addressId);
        ResultSet resultSet = statement.executeQuery();
        Address address = null;
        while (resultSet.next()){
            String province = resultSet.getString("province");
            String city = resultSet.getString("city");
            String status = resultSet.getString("status");
            String street = resultSet.getString("street");
            String addressInfo = resultSet.getString("address_info");
            address = new Address(addressId,province,city,status,street,addressInfo);
            break;
        }



        resultSet.close();
        statement.close();
        return address;
    }
}
